package com.stedu.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.stedu.bean.Owner;
import com.stedu.mapper.OwnerMapper;

import java.util.ArrayList;
import java.util.List;

public class DataListenr extends AnalysisEventListener<Owner> {
    //每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 100;
    private OwnerMapper ownerMapper;

    public DataListenr(OwnerMapper ownerMapper){
        this.ownerMapper = ownerMapper;
    }

    List<Owner> ownerList = new ArrayList<>();
    //读取数据会执行这方法
    @Override
    public void invoke(Owner owner, AnalysisContext analysisContext) {
        ownerList.add(owner);
        if (ownerList.size() >= BATCH_COUNT){
            ownerList.clear();
        }
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
    private void saveData(){
        for (Owner owner : ownerList) {
            ownerMapper.insert(owner);
        }
        System.out.println("存储数据库成功");
    }
}